﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace LiteQueryWPF.Controls
{
    /// <summary>
    /// FuncPanel.xaml 的交互逻辑
    /// </summary>
    public partial class FuncPanel : UserControl
    {
        QueryPanel _query;
        DataPanel _data;

        Entities.Config config;
        public Entities.Config Config
        {
            get { return config; }
            set { config = value; }
        }

        Entities.Func func;
        public Entities.Func PanelInfo
        {
            get { return func; }
            set { func = value; }
        }

        FuncPanelHelper.FuncPanel funcPanel;


        public FuncPanel()
        {
            InitializeComponent();
            funcPanel = new FuncPanelHelper.FuncPanel();
        }

        public FuncPanel(Entities.Func f, Entities.Config cfg)
        {
            InitializeComponent();
            this.PanelInfo = f;
            this.Config = cfg;
            this.grid.RowDefinitions[0].Height = new GridLength( f.Query.Heigth);
            funcPanel = new FuncPanelHelper.FuncPanel();

            FuncPanel_Load();
        }

        // 初始化面板
        private void FuncPanel_Load()
        {
            _query = new Controls.QueryPanel(func.Query);
            _data = new Controls.DataPanel(func.DataSql);
            this.grid.Children.Add(_query);
            this.grid.Children.Add(_data);
            Grid.SetRow(_query, 0);
            Grid.SetRow(_data, 1);
        }

        public bool Query()
        {
            var sql = _data.DataSql.Sql + _query.Query.GetWhereSQL(_data.DataSql.HasWhere);

            var ret = funcPanel.Query(this.Config.DataSource, sql);
            if (ret == null)
                return false;
            // 绑定数据
            _data.DataSource = ret.Tables[0];
            return true;
        }

        public bool Export(string path)
        {
            if (funcPanel.ExportToExcel(_data.DataSource, path).Item1)
                return true;
            else
                return false;
        }
    }
}
